package com.lj.demo.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lj.demo.commonutils.JwtUtils;
import com.lj.demo.commonutils.R;
import com.lj.demo.commonutils.UcenterMember;
import com.lj.demo.eduservice.client.UcenterClient;
import com.lj.demo.eduservice.entity.EduComment;
import com.lj.demo.eduservice.service.EduCommentService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author liujiang
 * @since 2020-12-29
 */
@RestController
@RequestMapping("/eduservice/eduComment")
//@CrossOrigin
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;

    @Autowired
    private UcenterClient ucenterClient;

    //根据id查询评论分页列表
    @ApiOperation(value = "评论分页列表")
    @GetMapping("{page}/{limit}")
    public R index(@PathVariable Long page,
                   @PathVariable Long limit,
                   String courseId){
        Page<EduComment> commentPage = new Page<>(page,limit);
        QueryWrapper<EduComment> wrapper = new QueryWrapper();
        wrapper.eq("courseId",courseId);

        commentService.page(commentPage,wrapper);
        List<EduComment> commentList = commentPage.getRecords();

        Map<String,Object> map = new HashMap<>();
        map.put("items",commentList);
        map.put("current",commentPage.getCurrent());
        map.put("pages", commentPage.getPages());
        map.put("size", commentPage.getSize());
        map.put("total", commentPage.getTotal());
        map.put("hasNext", commentPage.hasNext());
        map.put("hasPrevious", commentPage.hasPrevious());

        return R.ok().data(map);
    }

    @ApiOperation(value = "添加评论")
    @PostMapping("auth/save")
    public R save(@RequestBody EduComment eduComment, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (!StringUtils.isEmpty(memberId)){
            return R.error().code(28004).message("请登录");
        }
        eduComment.setMemberId(memberId);

        UcenterMember ucenterInfo = ucenterClient.getInfo(memberId);

        eduComment.setNickname(ucenterInfo.getNickname());
        eduComment.setAvatar(ucenterInfo.getAvatar());
        commentService.save(eduComment);
        return R.ok();
    }


}

